package com.gitee.kenewstar.utils;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author kenewstar
 * @date 2021/7/1
 */
public abstract class FunctionUtil {

	private static final String WRITE_REPLACE = "writeReplace";
	private static final String IS  = "is";
	private static final String GET = "get";

	/**
	 * 获取方法引用对应的全列名称
	 * User::getName ---> user.name
	 * @param column 函数式接口
	 * @return 全列名
	 */
	public static String getFieldName(Serializable column) {
		Method method;
		SerializedLambda lambda;
		String fieldName = null;
		try {
			method = column.getClass().getDeclaredMethod(WRITE_REPLACE);
			method.setAccessible(Boolean.TRUE);
			lambda = (SerializedLambda) method.invoke(column);
			fieldName = resolveLambda(lambda);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fieldName;
	}

	/**
	 * lambda解析
	 * @param lambda lambda
	 * @return 全列名
	 */
	private static String resolveLambda(SerializedLambda lambda) {
		String methodName = lambda.getImplMethodName();
		String tableName = "";
		String simpleName = "";
		if (Objects.nonNull(methodName) && methodName.startsWith(IS)) {
			simpleName = methodName.substring(2, 3).toLowerCase() +
					methodName.substring(3);
		}
		if (Objects.nonNull(methodName)&& methodName.startsWith(GET)) {
			simpleName = methodName.substring(3, 4).toLowerCase() +
					methodName.substring(4);
		}
		String implClass = lambda.getImplClass();
		String className = implClass.replace('/', '.');

		return simpleName;
	}

}
